package com.aiyige.utils.crash;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.aiyige.BuildConfig;
import com.aiyige.MyApp;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.model.AiyigeExceptionModel;
import com.aiyige.model.request.ExceptionSubmitRequest;
import com.aiyige.utils.AppUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class CrashUtils {

    public static String address_info = "";


    public class LogEntity {
        public String userId = "0";
        public String device = Build.BRAND;//获取手机品牌;
        public String deviceType = Build.MODEL;//设备型号;
        public String deviceCode = AppUtils.getIMeiString(getContext());//系统唯一吗;
        public String language = getContext().getResources().getConfiguration().locale.getCountry();
        public String os = "安卓系统";
        public String osVersion = Build.VERSION.RELEASE;//手机当前系统;
        public String netConnected = AppUtils.isNetworkAvailable(getContext()) ? "1" : "0";
        public String netType = getNetworkType(getContext());
        public String appVersion = getCurrentVersion(getContext());
        public String reportText;
        public String reportTime = (System.currentTimeMillis() / 1000) + "";


        public void setReportText(String logText) {
            reportText = logText;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public LogEntity() {

        }

        public LogEntity(String userIdOrPhoneNumber, String logString) {
            userId = userIdOrPhoneNumber;
            reportText = logString;
        }

        @Override
        public String toString() {
            return "LogEntity{" +
                    "userId='" + userId + '\'' +
                    ", device='" + device + '\'' +
                    ", deviceType='" + deviceType + '\'' +
                    ", deviceCode='" + deviceCode + '\'' +
                    ", language='" + language + '\'' +
                    ", os='" + os + '\'' +
                    ", osVersion='" + osVersion + '\'' +
                    ", netConnected='" + netConnected + '\'' +
                    ", netType='" + netType + '\'' +
                    ", appVersion='" + appVersion + '\'' +
                    ", reportText='" + reportText + '\'' +
                    ", reportTime='" + reportTime + '\'' +
                    '}';
        }
    }

    public void netSubmitLog(final String type, final String info, final int rating) {
//        if (BuildConfig.DEBUG) {
//            return;
//        }
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {

                String content = info;
                AiyigeExceptionModel model = new AiyigeExceptionModel();
                model.setType(type);
                model.setInfo(content);
                model.setRating(rating);
                String json = JsonUtil.toString(model);
                Log.e("xcjson",json);
                ExceptionSubmitRequest.newBuilder().aiyigeExceptionModel(model).build().enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (response != null && response.isSuccessful()) {
                            try {
                                String resBody = response.body().string();
                                Log.e("aiyigeException", "日志上传成功"+resBody);
                                if (BuildConfig.DEBUG) {
//                                    ToastX.show("日志上传成功"+resBody);
                                    return;
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        } else {
                            String resBody = null;
                            try {
                                resBody = response.errorBody().string();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            Log.e("aiyigeException", "日志上传成功"+resBody);
                        }

                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.e("aiyigeException", "日志上传失败了"+t != null ? t.toString():"");
                    }
                });
            }
        });
        thread.start();

    }

    private static CrashUtils INSTANCE;

    private CrashUtils() {
    }

    public static CrashUtils getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new CrashUtils();
        }
        return INSTANCE;
    }


    private Context getContext() {
        return MyApp.getAppContext();
    }

    public void addLogToSdCard(String log) {
        if (log == null) {
            return;
        }


//        String fileName = "wudao-log.log";
//        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            String path = Environment.getExternalStorageDirectory() + File.separator + "aiyige" + File.separator;
//            File dir = new File(path);
//            if (!dir.exists()) {
//                dir.mkdirs();
//            }
//            String time = TimeUtils.dateToYYYYMMDDHHSS(System.currentTimeMillis());
//            log = time + "\n" + log + "\n\n";
//            FileWriter fw = null;
//            try {
//                //如果文件存在，则追加内容；如果文件不存在，则创建文件
//                File f = new File(path + fileName);
//                fw = new FileWriter(f, true);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            if (fw == null) {
//                return;
//            }
//            try {
//                PrintWriter pw = new PrintWriter(fw);
//                pw.println(log);
//                pw.flush();
//                fw.flush();
//                pw.close();
//                fw.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
    }


    public static String getNetworkType(Context context) {
        String strNetworkType = "";
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                strNetworkType = "WIFI";
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                String _strSubTypeName = networkInfo.getSubtypeName();

                // TD-SCDMA networkType is 17
                int networkType = networkInfo.getSubtype();
                switch (networkType) {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_1xRTT:
                    case TelephonyManager.NETWORK_TYPE_IDEN: // api<8 : replace by
                        // 11
                        strNetworkType = "2G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_UMTS:
                    case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    case TelephonyManager.NETWORK_TYPE_HSDPA:
                    case TelephonyManager.NETWORK_TYPE_HSUPA:
                    case TelephonyManager.NETWORK_TYPE_HSPA:
                    case TelephonyManager.NETWORK_TYPE_EVDO_B: // api<9 : replace by
                        // 14
                    case TelephonyManager.NETWORK_TYPE_EHRPD: // api<11 : replace by
                        // 12
                    case TelephonyManager.NETWORK_TYPE_HSPAP: // api<13 : replace by
                        // 15
                        strNetworkType = "3G";
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE: // api<11 : replace by
                        // 13
                        strNetworkType = "4G";
                        break;
                    default:
                        // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
                        if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA")
                                || _strSubTypeName.equalsIgnoreCase("WCDMA")
                                || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                            strNetworkType = "3G";
                        } else {
                            strNetworkType = _strSubTypeName;
                        }

                        break;
                }
            }
        }
        return strNetworkType;
    }

    /**
     * 获取当前版本
     *
     * @param context
     * @return
     */
    public static String getCurrentVersion(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            String version = packInfo.versionName;
            return version;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    private String getDate() {
        long timestamp = System.currentTimeMillis();
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = formatter.format(new Date());
        return time;
    }

    public static String toURLEncoded(String paramString) {
        if (paramString == null || paramString.equals("")) {
            return "";
        }

        try {
            String str = new String(paramString.getBytes(), "UTF-8");
            str = URLEncoder.encode(str, "UTF-8");
            return str;
        } catch (Exception localException) {
        }

        return "";
    }


    /**
     * 获取外网的IP(要访问Url，要放到后台线程里处理)
     *
     * @param @return
     * @return String
     * @throws
     * @Title: GetNetIp
     * @Description:
     */
    public static void getNetIp() {
        if (!TextUtils.isEmpty(address_info)) {
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL infoUrl = null;
                InputStream inStream = null;

                HttpURLConnection httpConnection = null;
                try {
//            infoUrl = new URL("http://ip168.com/");
                    infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
                    URLConnection connection = infoUrl.openConnection();
                    httpConnection = (HttpURLConnection) connection;
                    int responseCode = httpConnection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        inStream = httpConnection.getInputStream();
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(inStream, "utf-8"));
                        StringBuilder strber = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                            strber.append(line + "\n");
                        }
                        address_info = strber.toString();
                        if (!TextUtils.isEmpty(address_info) && address_info.startsWith("var returnCitySN = ")) {
                            address_info = address_info.replace("var returnCitySN = ", "");
                            address_info = address_info.replace("\"", "");
                            address_info = address_info.replace(";\n", "");
                        }
//                        Pattern pattern = Pattern
//                                .compile("((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))");
//                        Matcher matcher = pattern.matcher(strber.toString());
//                        if (matcher.find()) {
//                            address_info = matcher.group();
//                        }
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        inStream.close();
                        httpConnection.disconnect();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                Log.e("getNetIp", address_info);
            }
        }).start();

    }
}
